package cn.appsys.controller.deve;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;

import cn.appsys.constants.Constants;
import cn.appsys.pojo.AppCategory;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.AppVersion;
import cn.appsys.pojo.DataDictionary;
import cn.appsys.pojo.DevUser;
import cn.appsys.pojo.Page;
import cn.appsys.service.deve.AppInfoService;
import cn.appsys.service.deve.AppVersionService;
import cn.appsys.service.deve.CategoryService;

@Controller
@RequestMapping("/appInfo")
public class AppInfoController {
	@Resource
	private AppInfoService appInfoService;
	@Resource
	private CategoryService categoryService;
	@Resource
	private AppVersionService appVersionService;
	//分页显示APP待审核查询列表
	@RequestMapping("/appList")
	public String appList(
		@RequestParam(value = "querySoftwareName",required = false)String querySoftwareName,
		@RequestParam(value = "queryFlatformId",required = false)Integer queryFlatformId,
		@RequestParam(value = "queryStatus",required = false)Integer queryStatus,
		@RequestParam(value = "queryCategoryLevel1",required = false)Integer queryCategoryLevel1,
		@RequestParam(value = "queryCategoryLevel2",required = false)Integer queryCategoryLevel2,
		@RequestParam(value = "queryCategoryLevel3",required = false)Integer queryCategoryLevel3,
		@RequestParam(value = "pageIndex",required = false,defaultValue = "1")Integer pageIndex,Model model) {
		//总记录数
		int totalCount = appInfoService.queryTotalCount(querySoftwareName, queryStatus, queryFlatformId, queryCategoryLevel1, queryCategoryLevel2, queryCategoryLevel3);
		//page 实体类
		Page page = new Page();
		page.setPageSize(5); //显示多少 条数据 
		page.setCurrPageNo(pageIndex); //当前页
		page.setTotalCount(totalCount);//总记录数
		//分页起 始位置偏移量
		Integer from = (page.getCurrentPageNo() - 1) * page.getPageSize();
		//分页查询App信息列表
		List<AppInfo> appInfoList = appInfoService.queryAppInfoPage(querySoftwareName, queryStatus, queryFlatformId, queryCategoryLevel1, queryCategoryLevel2, queryCategoryLevel3, from,page.getPageSize());
		//状态信息
		List<DataDictionary> statusList = appInfoService.dataDictionaryStatusList();
		//所属平台
		List<DataDictionary> flatFormList = appInfoService.dataDictionaryList("");
		//一级分类
		List<AppCategory> categoryLevel1List = categoryService.queryByParentId(null);
		List<AppCategory> categoryLevel2List = null;
		List<AppCategory> categoryLevel3List = null;
		System.out.println(queryCategoryLevel2);
		//二级分类
		if(queryCategoryLevel2 != null && queryCategoryLevel1 != 0) {
			categoryLevel2List = categoryService.queryByParentId(queryCategoryLevel2);
		}
		//三级分类
		if(queryCategoryLevel3 != null && queryCategoryLevel2 != 0) {
			categoryLevel3List = categoryService.queryByParentId(queryCategoryLevel3);
		}
		model.addAttribute("statusList", statusList);
		model.addAttribute("flatFormList", flatFormList);
		model.addAttribute("categoryLevel1List", categoryLevel1List);
		model.addAttribute("categoryLevel2List", categoryLevel2List);
		model.addAttribute("categoryLevel3List", categoryLevel3List);
		model.addAttribute("appInfoList", appInfoList);
		model.addAttribute("pages", page);
		//保存查询条件
		model.addAttribute("querySoftwareName", querySoftwareName);
		model.addAttribute("queryflatformId", queryFlatformId);
		model.addAttribute("queryCategoryLevel1", queryCategoryLevel1);
		model.addAttribute("queryCategoryLevel2", queryCategoryLevel2);
		model.addAttribute("queryCategoryLevel3", queryCategoryLevel3);
		return "developer/appinfolist";
	}
	//二三级分类下拉框
		@RequestMapping(value = "/AppCategoryList2",method = RequestMethod.GET)
		@ResponseBody
		public Object AppCategoryList2(@RequestParam("pid")Integer pid) {
			List<AppCategory> list = categoryService.queryByParentId(pid);
			return JSONArray.toJSONString(list);
		}
		/**
		 * 跳转到app新增页面
		 * 
		 * @return
		 */
		@RequestMapping("/toAppInfoAdd")
		public String toAppInfoAdd() {
			return "developer/appinfoadd";
		}
		/**
		 * 异步验证APKName是否存在
		 * 
		 * @param APKName
		 * @return
		 */
		@RequestMapping(value = "/ajaxApkNameIsExist", method = RequestMethod.GET)
		@ResponseBody
		public Object ajaxApkNameIsExist(@RequestParam("APKName") String APKName) {
			Map<String, String> map = new HashMap<String, String>();
			if (StringUtils.isNullOrEmpty(APKName)) {// 非空验证
				map.put("APKName", "empty");
			} else {// 不为空就根据apkName查询
				AppInfo app = appInfoService.queryAppInfoByAPKName(APKName);
				if (app != null) {// 如果有数据，就代表apkname已经存在
					map.put("APKName", "exist");
				} else {// 没有数据就代表apkname可用
					map.put("APKName", "noexist");
				}
			}
			return map;
		}
		/**
		 * 保存新增app基础信息
		 * @param appInfo
		 * @param session
		 * @param request
		 * @param attach
		 * @return
		 */
		@RequestMapping(value = "/saveAppInfo")
		public String saveAppInfo(
				AppInfo appInfo, 
				HttpSession session,
				HttpServletRequest request,
				@RequestParam("a_logoPicPath") MultipartFile attach) {
			
			String logoPicPath = ""; // 用于保存图片相对路径格式如：/AppInfoSystem/statics/uploadfiles/com.lbe.security.jpg
			String logoLocPath = ""; // 用于保存图片的绝对路径
			
			if (!attach.isEmpty()) { // 不为空的情况，我们进行文件上传 statics\\uploadfiles
				
				// path的值格式为：G:\\tool\\01-zip\\apache-tomcat-7.0.62\\webapps\\AppInfoSystem\\statics\\uploadfiles
				String path = request.getSession().getServletContext()
						.getRealPath("statics" + File.separator + "uploadfiles");// 获取文件上传所需要的路径。
				
				String oldFileName = attach.getOriginalFilename(); // 得到上传图片的原文件名
				
				String suffix = FilenameUtils.getExtension(oldFileName);// 得到原文件的后缀
				if (attach.getSize() > 5000000) { // 如果上传文件的大小超过500kb
					request.setAttribute("fileUploadError", "* 上传文件的大小超过500kb，上传失败！");
				} else if (suffix.equalsIgnoreCase("jpg")
						|| suffix.equalsIgnoreCase("png")
						|| suffix.equalsIgnoreCase("jpeg")
						|| suffix.equalsIgnoreCase("pneg")) {
					// 判断用户上传的文件格式是否是jpg、png、jpeg、pneg格式
					String fileName = appInfo.getAPKName() + ".jpg";// 获取上传之后的文件名字，因为
																	// APKName是唯一
					File file = new File(path, fileName); // 根据文件对象
					if (!file.exists()) { // 如果文件对象不存在，那么就创建这个目录
						file.mkdirs(); // 创建这个目录
					}
					try {
						attach.transferTo(file);// 将attach上传到指定的目录中去
					} catch (IllegalStateException | IOException e) {
						request.setAttribute("fileUploadError", "* 文件上传失败");
						e.printStackTrace();
					}
					logoPicPath = request.getContextPath()
							+ "/statics/uploadfiles/" + fileName; // 用于保存图片相对路径格式如：/AppInfoSystem/statics/uploadfiles/com.lbe.security.jpg
					logoLocPath = path + File.separator + fileName; // 保存的是图片的绝对路径
				}
			}
			// 在进行新增操作时，createdBy及creationDate赋值
			appInfo.setCreatedBy(((DevUser) session
					.getAttribute(Constants.DEV_USER_SESSION)).getId()); // 创建者的用户id
			appInfo.setCreationDate(new Date()); // 新增时间
			appInfo.setLogoLocPath(logoLocPath);
			appInfo.setLogoPicPath(logoPicPath);
			int result = appInfoService.addAppInfo(appInfo);
			if (result > 0) {
				return "redirect:/appInfo/appList"; // 新增成功跳转到app列表信息页面
			} else {
				return "developer/appinfoadd"; // 新增失败又跳转回新增页面
			}

		}
		/**
		 * ajax异步查询平台列表
		 * @param typeCode
		 * @return
		 */
		@RequestMapping(value="/ajaxPingTai",method = RequestMethod.GET)
		@ResponseBody
		public Object ajaxPingtai(@RequestParam("tcode") String typeCode){
			//通过typeData查询字典表
			List<DataDictionary> list = appInfoService.dataDictionaryList(typeCode);
			return list;
		}
		//修改页面
		@RequestMapping("/queryAppInfo/{id}")
		public String queryAppInfo(@PathVariable Integer id, Model model, HttpSession session) {
			AppInfo appInfo = appInfoService.queryById(id);
			session.getAttribute(Constants.DEV_USER_SESSION);
			model.addAttribute("appInfo",appInfo);
			return "developer/appinfomodify";
		}
		//删除图片
		@RequestMapping(value = "/delfile", method = RequestMethod.GET)
		@ResponseBody
		public Object delfile(@RequestParam(value = "id", required = false) Integer id) {
			Map<String, String> map = new HashMap<String, String>();
			if (id == null || id == 0) {
				map.put("result", "failed");
			} else {
				AppInfo appInfo = appInfoService.queryById(id);// 根据id查询appinfo详情信息
				File file = new File(appInfo.getLogoLocPath());
				if (file.exists()) {
					if (file.delete()) { // 将服务器中的LOGO图片从文件夹中删除。
						// 将数据库中appinfo表里的logoLocPath与logoPicPath字段给清空。
						if (appInfoService.updateLogoPathById(id) > 0) {
							map.put("result", "success");
						}
					}
				} else {
					map.put("result", "fileNoExist"); // 服务器上的图片文件不存在，删除失败
				}
			}
			return map;
		}
		
		// 修改
		@RequestMapping("/appinfomodify")
		public String appinfomodify(Model model, AppInfo appInfo, HttpSession session, HttpServletRequest request,
				@RequestParam(value = "attach", required = false) MultipartFile attach) {
			session.getAttribute(Constants.DEV_USER_SESSION);
			String logoLocPath = ""; // 上传图片的绝对路径
			String logoPicPath = ""; // 上传图片的相对路径
			if (!attach.isEmpty()) {
				// 获取文件上传所需要的路径
				String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "images");
				String oldFileName = attach.getOriginalFilename(); // 得到原文件名
				String suffix = FilenameUtils.getExtension(oldFileName); // 原文件的后缀
				if (attach.getSize() > 5000000) {
					model.addAttribute("fileUploadError", "* 上传文件的大小超过500KB，上传失败！");
				} else if (suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("png")
						|| suffix.equalsIgnoreCase("jepg") || suffix.equalsIgnoreCase("pneg")) {// 上传图片格式
					String fileName = appInfo.getAPKName() + ".jpg";// 上传LOGO图片命名:apk名称.apk
					File file = new File(path, fileName);
					if (!file.exists()) {
						file.mkdirs();
					}
					try {
						attach.transferTo(file);
					} catch (IllegalStateException | IOException e) {
						model.addAttribute("fileUploadError", "* 文件上传失败");
						e.printStackTrace();
					}
					logoPicPath = request.getContextPath() + "/statics/images/" + fileName;
					logoLocPath = path + File.separator + fileName;
				}
			}

			DevUser loginUser = (DevUser) session.getAttribute(Constants.DEV_USER_SESSION);
			appInfo.setModifyBy(loginUser.getId()); // modifyBy 修改者的编号 ，以当前登录用户的ID作为当前修改的modifyBy
			appInfo.setModifyDate(new Date()); // 修改时间为当前时间
			appInfo.setLogoLocPath(logoLocPath);
			appInfo.setLogoPicPath(logoPicPath);
			boolean isFlag = appInfoService.appinfomodify(appInfo);
			if (isFlag) {
				return "redirect:/appInfo/appList"; // 修改成功后，跳转以用户列表页面
			} else {
				// 修改失败，现跳回修改页面
				return "redirect:/dev/getId/" + appInfo.getId();
			}

		}
		//查看App基础信息
		@RequestMapping("/appview/{id}")
		public String appview(@PathVariable Integer id, Model model, HttpSession session) {
			AppInfo appInfo = appInfoService.queryById(id);
			List<AppVersion> list = appVersionService.getAppVersionById(id);
			session.getAttribute(Constants.DEV_USER_SESSION);
			model.addAttribute("appInfo",appInfo);
			model.addAttribute("appVersionList",list);
			return "developer/appinfoview";
				}
}
